<template>
	<view>

		<!-- IOS 未开启充值  或 不是投链用户 不展示充值 -->
		<view v-if="System == 'iOS'&&(!appInfo.iospay||(!userInfo.tfid||userInfo.tfid==0))">
			<view >
				<u-empty mode="permission" icon="http://cdn.uviewui.com/uview/empty/permission.png"
					text="由于相关规范，ios功能暂不可用" textColor="#191919" textSize="22px">
				</u-empty>
			</view>
		</view>
		<view v-else>
			<!-- 选项卡   -->
				<view>
					<view class="tn-flex tn-flex-direction-row tn-flex-row-center">
						<view class="tn-flex tn-flex-direction-column tn-flex-col-center tn-flex-row-center tn-margin-sm"
							v-for="(tab,idx) in tabList" @click="changeTab(idx)">
							<view :class="tabIndex==idx?'dm-main-text-color tn-text-bold tn-text-xl':'tn-color-white'">
								{{ tab.name }}</view>
							<image v-if="tabIndex==idx" src="/static/images/recharge/chosen_tab.svg"
								style="height: 13rpx;width: 160rpx" />
						</view>
					</view>
				</view>
				<!-- 金豆信息   -->
				<view v-if="tabIndex==0">
					<view class="tn-flex tn-flex-row-between tn-text-xl dm-margin-left-right " style="color: #FA9E8C"
						v-if="isRechargePage">
						<view class="tn-flex tn-flex-col-center">
							<image src="/static/images/my/bag.svg" style="height: 50px;width: 50px" />
							<view>可用金豆：{{userBalance}}</view>
						</view>
						<view class="tn-flex tn-flex-col-center">
							<view>可用赠送金豆：{{userGiftBalance}}</view>
						</view>
					</view>
				</view>
				<!-- 权益说明   -->
				<view v-else>
					<view class="tn-flex tn-flex-row-center">
						<image src="/static/images/recharge/vip.svg" style="width: 40px;height: 20px" />
						<text class="tn-text-lg" style="color: #FA9E8C" v-if="isVip">会员到期时间：{{vipExpireTime*1000|formatDate}}</text>
						<text class="tn-text-lg" style="color: #FA9E8C" v-else>开通会员立享随心看剧</text>
					</view>
					<view class="tn-flex tn-flex-row-center  tn-color-white">
						<view class="tn-flex tn-flex-direction-row tn-flex-col-center tn-margin" v-for="(item,idx) in rights">
							<image src="/static/images/recharge/checked.svg"
								style="height: 15px;width: 15px; margin-right: 5px" />
							<view>{{ item }}</view>
						</view>
					</view>
				</view>

				<view>
					<!-- 金豆卡片   -->
					<view v-if="tabList[tabIndex].name=='金豆充值'">
						<u-grid :col="2" align="left" :border="false">
							<u-grid-item v-for="(item,index) in beanRechargeList" :key="index" @click="confirmPay(index)"
								class="tn-padding-top-sm" bg-color="transparent" :custom-style="{padding:'5px 0'}">
								<view class="bean-card-box" :class="index==0?'box-active':''">
									<view class="left-tag-box" v-if="item.judge==2">
										<image src="/static/images/recharge/left_yellow_tag.svg" class="left-tag" />
										<text>限时</text>
									</view>
									<view class="left-tag-box" v-else-if="item.judge==1">
										<image src="/static/images/recharge/left_green_tag.svg" class="left-tag" />
										<text>超值</text>
									</view>
									<view class="left-tag-box" v-else-if="item.judge==3">
										<image src="/static/images/recharge/left_green_tag.svg" class="left-tag" />
										<text>赠</text>
									</view>
									<view class="left-tag-box" v-else-if="item.judge==4">
										<image src="/static/images/recharge/left_yellow_tag.svg" class="left-tag" />
										<text>折扣</text>
									</view>
									<view class="content-box ">
										<view class="price">
											<text class="tn-text-sm">￥</text>
											<text>{{ item.recharge_amount/100 }}</text>
										</view>
										<view class="title">
											{{ item.recharge_text }}
										</view>
										<view class="tip" v-if="item.gift>0">
											多赠送{{item.gift/100}}元
										</view>
										<view class="finger" v-if="index==0">
											<image src="/static/images/recharge/finger.svg" />
										</view>
									</view>
								</view>
							</u-grid-item>
						</u-grid>
					</view>
					<!-- 会员卡片   -->
					<view v-else>
						<u-grid :col="3" align="left" :border="false">
							<u-grid-item v-for="(item,index) in vipRechargeList" :key="index" @click="confirmPay(index)"
								bg-color="transparent" :custom-style="{padding:'5px 0'}">
								<view class="vip-card-box" :class="index==0?'box-active':''">
									<view class="top-tag-box">
										<image src="/static/images/recharge/top_red_tag.svg" class="top-tag" />
										<text>{{item.subject}}</text>
									</view>
									<view class="left-tag-box" v-if="!item.giftBeansPermanent">
										<image src="/static/images/recharge/left_yellow_tag.svg" class="left-tag" />
										<text>限时</text>
									</view>
									<view class="left-tag-box" v-else-if="item.greatValue">
										<image src="/static/images/recharge/left_green_tag.svg" class="left-tag" />
										<text>超值</text>
									</view>
									<view class="content-box ">
										<view class="title">
											{{ item.recharge_text }}
										</view>
										<view class="price" :class="index==0?'price-active':''">
											<text class="tn-text-sm">￥</text>
											<text>{{ item.recharge_amount/100 }}</text>
										</view>
										<view class="old-price">
											<text>￥{{ item.recharge_amount/20 }}</text>
										</view>
										<view class="tip">
											{{ item.subject }}随心看
										</view>
									</view>
								</view>
							</u-grid-item>
						</u-grid>
					</view>
				</view>

				<view style="background: #242424;position: fixed;bottom: 0;width: 100%" v-if="!isRechargePage">
					<view class="tn-flex tn-flex-row-center tn-flex-row-center tn-color-gray dm-margin-top-bottom-xs"
						@click="tn('/pages_sub/recharge/recharge')">充值说明></view>
				</view>


<!--				<view v-if="isRechargePage">-->
					<!-- 充值说明   -->
					<view>
						<u-gap height="30"></u-gap>
						<view>
							<view class="explanation">充值代表接收《<span class="tn-color-white" @click="toPrivacy('recharge')">充值规则协议</span>》和《<span class="tn-color-white" @click="toPrivacy('memeber')">会员服务协议</span>》</view>
							<view class="explanation">充值说明：</view>
							<view class="explanation">1.充值后5分钟内到账，入未到账请联系客服</view>
							<view class="explanation">2.金豆或会员充值成功后不支持退款</view>
							<view class="explanation">3.赠送金豆会优先消耗，时效7天过期后自动清除</view>
							<view class="explanation">4.成为会员可免费看所有剧集</view>
							<view class="explanation">5.全集解锁卡支持单部剧全剧集解锁</view>
						</view>
            <u-gap height="30"></u-gap>
					</view>

					<!--      &lt;!&ndash; 支付按钮   &ndash;&gt;-->
					<!--      <view class="pay-box tn-flex tn-flex-row-center tn-flex-col-center">-->
					<!--        <tn-button backgroundColor="#FF1C57" fontColor="tn-color-white" shape="round" size="lg" style="width: 80%" @click="confirmPay">-->
					<!--          {{ payBtnText }}</tn-button>-->
					<!--      </view>-->
<!--				</view>-->

			<!-- H5支付方式弹窗开始 -->
			<view v-show="showPayChannel" style="position: fixed;width: 100%;height: 100%;background-color: rgba(0, 0, 0, 0.5);
			z-index: 99999;top: 0;">
				<view style="background-color: white;bottom: 0;position: absolute;border-radius: 10px 10px 0 0;">
					<view style="padding: 0 10px 10px 5px;">
						<view style="font-size: 25px;cursor: pointer;width: 25px;padding-left: 10px;"
							@click="showPayChannel=false">x</view>
					</view>

					<view
						style="display: flex;align-items: center;justify-content: center;margin-top: 10px;margin-bottom: 30px;">
						<view style="font-size: 20px;">￥</view>
						<view style="font-weight: bold;font-size: 30px;">{{temp_item.recharge_amount/100}}</view>
					</view>
					<u-line length="750rpx"></u-line>
					<view>
						<radio-group>
							<view style="display: flex;justify-content: space-between;padding: 10px 20px;cursor: pointer;"
								@click="h5PayChannel='1'">
								<view style="display: flex;align-items: center;">
									<img style="width: 20px;margin-right: 5px;"
										src="https://mp-6c5504f1-e764-42f7-a299-946eaad4da31.cdn.bspapp.com/cloudstorage/97ba4ca2-0a64-40c2-8aa3-798d518c7541.png">
									微信支付
								</view>
								<view>
									<radio value="1" :checked="h5PayChannel == 1" />
								</view>
							</view>
							<view style="display: flex;justify-content: space-between;padding: 10px 20px;cursor: pointer;"
								@click="h5PayChannel='2'">
								<view style="display: flex;align-items: center;">
									<img style="width: 20px;margin-right: 5px;"
										src="https://mp-6c5504f1-e764-42f7-a299-946eaad4da31.cdn.bspapp.com/cloudstorage/ad998147-922b-4209-80f0-aff2b8d51c20.png">
									支付宝支付
								</view>
								<view>
									<radio value="2" :checked="h5PayChannel == 2" />
								</view>
							</view>
						</radio-group>
					</view>

					<view style="background-color: #FE2B54;text-align: center;color: white;height: 50px;line-height:50px;font-size: 18px;
					margin-top: 30px;width: 90%;margin-left: auto;margin-right: auto;margin-bottom: 10px;border-radius: 3px;
					cursor: pointer;" @click="confirmH5Pay()">
						确认支付
					</view>
				</view>
			</view>
			<!-- H5支付方式弹窗结束 -->

		</view>

	</view>
</template>

<script>
	import UGap from "../../uni_modules/uview-ui/components/u-gap/u-gap.vue";
	import common_mixin from '@/libs/mixin/common_mixin.js'
	import {
		createOrder,
		getMyUserInfo,
		wxpayH5
	} from "../../api/api";
	import {
		getnoncestr,
		setStorageSync
	} from "../../utils/utils";
	import Config from '@/utils/config.js';
	import store from "../../store";

	export default {
		mixins: [common_mixin],
		name: "recharge-list",
		components: {
			UGap
		},
		props: ['vipRechargeList', 'beanRechargeList', 'tvName', 'isRechargePage', 'toTabIndex'],
		data() {
			return {
				// 显示相关
				tabIndex: 0,
				tabList: [{
					name: "金豆充值"
				}, {
					name: "会员"
				}],
				rights: ["解锁全部短剧", "看剧无广告", "高清看剧", ], //权益
				payBtnText: "立即开通会员",
				payType: 'wxpay',
				userBalance: 0,
				userGiftBalance: 0,
				vipExpireTime: '',
				isVip: false,
				useVirtualPayment: false,
				// 数据相关
				vipRechargeIndex: 0,
				beanRechargeIndex: 0,
				vkPay: {
					queryPaymentAction: {
						name: "vk-pay", // 云函数名称
						action: "pay/queryPayment", // 路由模式下云函数地址
						actionKey: "action", // 路由模式下云函数地址的识别key
						dataKey: "data" // 路由模式下云函数请求参数的识别key
					},
					// PC支付的付款二维码地址 渲染二维码需要自己写，可以参考示例中的二维码组件 vk-uni-qrcode
					codeUrl: "",
					// 当前支付状态 0:等待发起支付 1:支付中 2:已支付
					status: 0,
					// 当前页面是否显示
					pageShow: true,
					// 启用轮询检测订单支付状态（仅h5支付有效）
					polling: true
				},
				isWeChat:Config.isWeChat,
				showPayChannel:false,
				temp_item:{},
				h5PayChannel:1,
				System:'',
				userInfo:{}
				//appInfo:{}
			};
		},
		created() {
			this.userInfo = uni.getStorageSync("userInfo");
			if (this.toTabIndex) {
				this.tabIndex = this.toTabIndex
			}
			this.vkPay.pageShow = true;
			this.refreshUserInfo();
			this.System = wx.getSystemInfoSync().system.startsWith('iOS') ? 'iOS' : 'Android';
			if (this.System != 'iOS' && this.appInfo.virtualPayment) {
				this.useVirtualPayment = true;
			}
		},

		methods: {
      toPrivacy(path) {
        console.log(path);
        var url  = '/pages_sub/webview/webview?path='+path;
        uni.navigateTo({
          url: url
        })
      },
			async refreshUserInfo() {
				let res = await this.$api.getMyUserInfo();
				this.userInfo = res.userinfo
				setStorageSync("userInfo", this.userInfo);
				store.commit('$tStore', {
					name: 'vuex_user',
					value: this.userInfo
				});
				this.userBalance = this.userInfo.balance;
				this.vipExpireTime = this.userInfo.plus_expire_time;
				this.userGiftBalance = this.getGiftBalance();
				this.isVip = this.checkVip();
			},
			confirmPay(index) {
				let userInfo = uni.getStorageSync("userInfo");
				if (!userInfo.mobile) {
					uni.navigateTo({
					    url: '/pages_sub/invite/bindphone?openRecharge=true'
					});
					return false;
				}
				let item;
				if (this.tabIndex == 0) {
					item = this.beanRechargeList[index]
				} else {
					item = this.vipRechargeList[index]
				}
				if(this.isWeChat){
					this.createOrder(item);
				}else{
					this.temp_item = item;
					this.showPayChannel = true;
					this.$forceUpdate();
				}
				console.log(this.temp_item);
			},
			confirmH5Pay(){
				console.log(this.temp_item,this.h5PayChannel);
				this.showPayChannel = false;
				this.createOrder(this.temp_item,true);
			},
			async createOrder(item,isH5=false) {
				const virtualPayment = this.useVirtualPayment ? 1 : 0;
				let platform;
				if(isH5){
					platform = this.h5PayChannel==1 ? 'h5_wxpay' : 'h5_alipay';
				}else{
					platform = 'wxmp';
				}
				let params = {
					recharge_id: item.id,
					tv_name: this.tvName || "直充", //记录本次充值来自哪部剧，无来源就是直充
					virtualPayment: virtualPayment,
					platform:platform,
					h5PayChannel:this.h5PayChannel
				};
				let res = await this.$api.createOrder(params);
				if(isH5){
					if(this.h5PayChannel==1){
						if(res.resultCode == 0 && res.status == 0){
							location.href = res.codeUrl;
						}
					}else{
						// 支付宝支付，这里只要提交表单
						// 创建一个新的div元素
						const div = document.createElement('div');
						// 渲染这个div中的表单（res.data.pay_img就是后端返回的表单）
						div.innerHTML = res;
						// 进行元素追加渲染
						document.body.appendChild(div);
						// 提交表单(alipaysubmit这个名字是和表单上的name一致的，要注意别搞错了)
						//document.forms['alipaysubmit'].submit();
						// 获取表单对象
						const form = div.querySelector('form');
						// 提交表单
						form.submit();
					}
				}else{
					if (!this.useVirtualPayment) {
						var that = this;
						uni.requestPayment({
							provider: 'wxpay',
							timeStamp: res.timeStamp,
							nonceStr: res.nonceStr,
							package: res.package,
							signType: res.signType,
							paySign: res.paySign,
							success:function(res) {
								console.log('success:' + JSON.stringify(res));
								uni.showToast({
									title: '支付成功',
									duration: 2000
								});
								setTimeout(async ()=>{
									await that.refreshUserInfo(); //刷新余额
									that.$emit('rechargesuccess', {});
								},1000);
							},
							fail: function(err) {
								console.log('fail:' + JSON.stringify(err));
							}
						});
					} else {
						//虚拟支付
						this.createVirtualPayment(res);
					}
				}
			},
			createVirtualPayment(orderinfo) {
				if (wx.getSystemInfoSync().SDKVersion < '2.33.0' && !wx.canIUse('requestVirtualPayment')) {
					uni.showModal({
						title: '提示', // 对话框的标题
						content: "客户端版本不支持虚拟支付模块，当前版本:" + wx.getAppBaseInfo().SDKVersion, // 对话框的内容
						showCancel: true, // 是否显示取消按钮，默认为 true
						cancelText: '取消', // 取消按钮的文字，默认为 "取消"
						cancelColor: '#000000', // 取消按钮的文字颜色，默认为 "#000000"
						confirmText: '确定', // 确定按钮的文字，默认为 "确定"
						confirmColor: '#3CC51F', // 确定按钮的文字颜色，默认为 "#3CC51F"
					});
					return false;
				}
				var that = this
				uni.login({
					provider: 'weixin', // 使用微信登录
					success: async function(loginRes) {
						const code = loginRes.code;
						const LoginRes = await this.$api.getEncodeCode({
							appid: orderinfo.appid,
							code: code
						});
						const session_key = LoginRes.session_key;
						const virtualPayRes = await this.$api.virtualPaySign({
							appid: orderinfo.appid,
							session_key: session_key,
							out_trade_no: orderinfo.out_trade_no,
							total_fee: orderinfo.recharge_amount
						});
						const paymentParams = {
							mode: 'short_series_coin',
							signData: virtualPayRes.postbody,
							signature: virtualPayRes.signature,
							paySig: virtualPayRes.paySig,
							async success(res) {
								//支付成功，通知后台发货
								const virtualPayNotifyxRes = await that.$api.virtualPayNotifyx({
									out_trade_no: orderinfo.out_trade_no,
									total_fee: orderinfo.recharge_amount
								});
								uni.showToast({
									title: '支付成功',
									duration: 2000
								});
								await that.refreshUserInfo(); //刷新余额
								that.$emit('rechargesuccess', {});
							},
							fail(res) {
								// 支付失败回调
								console.log('支付失败：', res);
								let titleStr = res.errCode == -2 ? "支付取消" : "错误码:" +
									res.errCode + ',错误提示：' + res.errMsg;
								uni.showModal({
									title: '提示', // 对话框的标题
									content: titleStr, // 对话框的内容
									showCancel: true, // 是否显示取消按钮，默认为 true
									cancelText: '取消', // dd，默认为 "取消"
									cancelColor: '#000000', // 取消按钮的文字颜色，默认为 "#000000"
									confirmText: '确定', // 确定按钮的文字，默认为 "确定"
									confirmColor: '#3CC51F', // 确定按钮的文字颜色，默认为 "#3CC51F"
									success: (res) => {
										if (res.confirm) {
											console.log('用户点击了确定');
											// 在这里执行用户点击确定后的操作
										} else if (res.cancel) {
											console.log('用户点击了取消');
											// 在这里执行用户点击取消后的操作
										}
									},
									fail: (err) => {

									},
									complete: () => {

									}
								});
							},
							complete() {
								// 支付结束回调（无论成功或失败都会执行）
								console.log('支付结束');
							}
						}
						wx.requestVirtualPayment(paymentParams);
					}.bind(this)
				});
			},
			changeTab(idx) {
				this.tabIndex = idx;
				this.vipRechargeIndex = 0;
				this.beanRechargeIndex = 0;

				// 修改支付按钮方案
				if (this.tabIndex == 0 && this.isVip) {
					this.payBtnText = "立即续期"
				} else {
					this.payBtnText = "立即开通会员"
				}
				if (this.tabIndex == 1) {
					this.payBtnText = "立即支付"
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.content {
		background: linear-gradient(180deg, #3A3A3A 0%, #000000 100%);
	}

	.tn-grid-item {
		background: none;
	}

	.vip-card-box {
		position: relative;
		margin: 10px;
		width: 110px;
		height: 140px;
		border-radius: 8px;
		background-color: grey;
		border: 2px solid #707070;

		.left-tag-box {
			position: absolute;
			left: -23px;
			top: 0;

			.left-tag {
				width: 60px;
				height: 120px;
			}

			text {
				position: absolute;
				left: 14px;
				top: 45px;
				writing-mode: tb-rl;
				color: #FFFFFF;
			}
		}

		.top-tag-box {
			position: absolute;
			left: -6px;
			top: -22px;

			.top-tag {
				width: 120px;
				height: 60px;
			}

			text {
				position: absolute;
				left: 33px;
				top: 16px;
				font-weight: bold;
				font-size: 12px;
				color: #FFFFFF;
			}
		}

		.content-box {
			margin: 30px 18px 18px 18px;
			text-align: center;

			.title {
				color: #FFFFFF;
				font-size: 16px;
				font-weight: bold;
			}

			.price {
				font-size: 22px;
				font-weight: bold;
				color: #FFFFFF;
			}

			.price-active {
				color: #FA0909;
			}

			.old-price {
				text-decoration: line-through;
				color: #565656;
				font-size: 12px
			}

			.tip {
				color: #FFFFFF;
				font-size: 12px;
			}
		}
	}

	.bean-card-box {
		position: relative;
		width: 160px;
		height: 90px;
		border-radius: 8px;
		background-color: #FFB144;
		border: 2px solid #707070;
		margin-bottom: 10px;

		.left-tag-box {
			position: absolute;
			left: -17px;
			top: -14px;

			.left-tag {
				width: 50px;
				height: 110px;
			}

			text {
				position: absolute;
				left: 10px;
				top: 40px;
				writing-mode: tb-rl;
				color: #FFFFFF;
			}
		}

		.content-box {
			margin: 6px 12px;
			text-align: center;

			.title {
				color: #FFFFFF;
				font-size: 12px;
			}

			.price {
				font-size: 22px;
				font-weight: bold;
				color: #FFFFFF;
			}

			.price-active {
				color: #FA0909;
			}

			.tip {
				color: #FF1C57;
				font-weight: bold;
				font-size: 12px;
			}
		}

		.finger {
			position: absolute;
			right: 0;
			bottom: 0;

			image {
				width: 37px;
				height: 27px;
			}
		}

	}

	.box-active {
		background-color: black;
		background: linear-gradient(180deg, #6C4A4A 0%, #200101 80%);
		border: 2px solid #FF1C57;
	}

	.pay-box {
		background-color: #47383C;
		height: 100px;
		display: flex;
		width: 100%;
		position: fixed;
		bottom: 0;
	}

	.explanation {
		color: #888;
		font-size: 22rpx;
		line-height: 40rpx;
		margin-left: 20rpx;
	}
</style>
